import "dart:io";

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import "package:word_range_client/pages/PadView.dart";
// 页面布局
import "package:word_range_client/pages/PhoneView.dart";
import "package:word_range_client/pages/WindowsView.dart";

import "../../main.dart";

class TopButtons extends StatelessWidget {
  const TopButtons({super.key});

  @override
  Widget build(BuildContext context) {
    return const Padding(
      padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          _LogoutButton(),
          _ThemeToggleButton(), // 新增：主题切换按钮
        ],
      ),
    );
  }
}

// 新增：主题切换按钮
class _ThemeToggleButton extends StatefulWidget {
  const _ThemeToggleButton({super.key});

  @override
  State<_ThemeToggleButton> createState() => _ThemeToggleButtonState();
}

class _ThemeToggleButtonState extends State<_ThemeToggleButton> {
  bool _isDarkMode = false;

  @override
  void initState() {
    _loadThemePreference();
    super.initState();
  }

  // 加载主题偏好
  Future<void> _loadThemePreference() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _isDarkMode = prefs.getBool('isDarkMode') ?? false;
    });
  }

  // 切换主题
  Future<void> _toggleTheme() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _isDarkMode = !_isDarkMode;
      prefs.setBool('isDarkMode', _isDarkMode);
    });

    // 通知应用主题已更改
    if (Platform.isAndroid || Platform.isIOS) {
      // 在移动端，重绘页面
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => MyApp(isDarkMode: _isDarkMode),
        ),
      );
    } else {
      // 在桌面端，重绘页面
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => WindowsView(isDarkMode: _isDarkMode),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return _TopButtonItem(
      icon: _isDarkMode ? Icons.light_mode : Icons.dark_mode,
      onPressed: _toggleTheme,
    );
  }
}

class _LogoutButton extends StatefulWidget {
  const _LogoutButton({super.key});

  @override
  State<_LogoutButton> createState() => _LogoutButtonState();
}

class _LogoutButtonState extends State<_LogoutButton> {

  Future<void> _logout() async {
    // 添加二次确认对话框
    bool confirm = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("退出登录"),
        content: const Text("您确定要退出登录吗？登出后将清除您在本地的所有未提交的数据！您的部分进度可能会丢失！"),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text("取消"),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text("确认"),
          ),
        ],
      ),
    );

    // 如果用户确认登出，则执行登出操作
    if (confirm == true) {
      final prefs = await SharedPreferences.getInstance();
      prefs.clear();  // 注销时清空本地数据！
      _toWelcomePage();
    }
  }

  Future<void> _toWelcomePage() async {
    final prefs = await SharedPreferences.getInstance();
    final isDarkMode = prefs.getBool('isDarkMode') ?? false;

    if(Platform.isAndroid){
      final bool isMobileLayout = MediaQuery.of(context).size.width < 600;
      if(isMobileLayout){
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => PhoneView(isDarkMode: isDarkMode)));
      }else{
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => PadView(isDarkMode: isDarkMode)));
      }
    }else{   // 目前只支持安卓、Windows
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => WindowsView(isDarkMode: isDarkMode)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return _TopButtonItem(
      icon: Icons.logout,
      onPressed: _logout,
    );
  }
}


class _TopButtonItem extends StatelessWidget {
  const _TopButtonItem({super.key, required this.icon, this.onPressed});

  final IconData icon;
  final VoidCallback? onPressed;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 50,width: 50,
      child: IconButton(
          onPressed: onPressed,
          icon: Icon(icon)
      ),
    );
  }
}
